﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XlDde;
using System.Collections.ObjectModel;
using RiskMan.DataClass.Models;
using TheControllerRisk.Settings;
using System.Windows.Forms;
using RiskMan.Views.Dialogs;
using System.Reflection;

namespace RiskMan.Providers.Channels
{
    class DDEChannelLimiteByAccount : XlDdeChannel
    {
        private ObservableCollection<LimitByAccountModel> observableCollection;

        public DDEChannelLimiteByAccount()
        {
            
        }

        protected override void ProcessTable(XlTable xt, string topic)
        {
            observableCollection = RiskMan.MainWindow.StaticLevel._dataProvider.LimitebyAccount;
            try
            {
                for (int i = 0; i < xt.Rows; i++)
                {
                    LimitByAccountModel tmp = new LimitByAccountModel();
                    List<String> names = new List<String>();

                    for ( int j = 0; j < xt.Columns; j++ )
                    {
                        xt.ReadValue( );
                        if ( Namespace.Count == 0 && i == 0 )
                        {
                            tmp = null;
                            names.Add( xt.StringValue );
                        }
                        else
                        {
                            if ( IsSend( xt ) == true )
                            {
                                try
                                {
                                    if ( Namespace [ j ] == "FIRMID" ) tmp.Company = xt.StringValue;
                                    if ( Namespace [ j ] == "TRDACCID" ) tmp.Account = xt.StringValue;
                                    if ( Namespace [ j ] == "LIMIT_TYPE" ) tmp.TypeLimit = xt.StringValue;
                                    if ( Namespace [ j ] == "LIQUIDITY_COEFF" ) tmp.Kmolotiluas = xt.FloatValue;
                                    if ( Namespace [ j ] == "CBP_PREV_LIMIT" ) tmp.LastLimitOpenPosition = xt.FloatValue;
                                    if ( Namespace [ j ] == "CBPLIMIT" ) tmp.LimitOpenPosition = xt.FloatValue;
                                    if ( Namespace [ j ] == "CBPLUSED" ) tmp.CurrentEmptyPosition = xt.FloatValue;
                                    if ( Namespace [ j ] == "CBPLUSED_FOR_ORDERS" ) tmp.CurrentEmptyOrder = xt.FloatValue;
                                    if ( Namespace [ j ] == "CBPLUSED_FOR_POSITIONS" ) tmp.CurrentEmptyOpen = xt.FloatValue;
                                    if ( Namespace [ j ] == "CBPLPLANNED" ) tmp.PlanEmptyPosition = xt.FloatValue;
                                    if ( Namespace [ j ] == "VARMARGIN" ) tmp.VariableMarga = xt.FloatValue;
                                    if ( Namespace [ j ] == "ACCRUEDINT" ) tmp.Dohod = xt.FloatValue;
                                    if ( Namespace [ j ] == "OPTIONS_PREMIUM" ) tmp.BonusByOption = xt.FloatValue;
                                    if ( Namespace [ j ] == "TS_COMISSION" ) tmp.BirgaSbor = xt.FloatValue;
                                    if ( Namespace [ j ] == "KGO" ) tmp.CountGO = xt.FloatValue;
                                }
                                catch ( ArgumentOutOfRangeException )
                                {
                                    string message = "\"Таблица ограничений по клиентским счетам\" в разных терминалах настроены по разному. \n\r" +
                                            "Для правильной настройки таблице ознакомьтесь с инструкцией." +
                                            "\n\rНеобходимо чтоб название и количество выводимых параметров совпадало.";
                                    string title = "Ошибка";

                                    if ( base.IsShowMessage == false )
                                    {
                                        base.IsShowMessage = true;
                                        new DialogMessage( message, title );
                                    }
                                    cfg.SetLog( message, RiskMan.MainWindow.StaticLevel.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod() );
                                }
                                catch ( Exception ex )
                                {
                                    new DialogMessage( ex.Message, "DDEChannelLimiteByAccount" );
                                }
                            }
                            else { tmp = null; }
                        }
                    }
                    if (tmp != null)
                    {
                        if (tmp.TypeLimit == cfg.ZalogMoney)
                            break;

                        bool tr = false;
                        for (int c = 0; c < observableCollection.Count; c++)
                        {
                            if (observableCollection[c].Account == tmp.Account && 
                                observableCollection[c].TypeLimit == tmp.TypeLimit && 
                                observableCollection[c].Company == tmp.Company)
                            {
                                tr = true;
                                observableCollection[c] = tmp;
                            }
                        }
                        if (tr == false)
                            observableCollection.Add(tmp);
                    }

                    if (names.Count > 0)
                        Namespace = new List<String>(names);
                }
            }
            catch (Exception ex)
            {
                new DialogOkCancel( ex.Message, "DDEChannelLimiteByAccount");
            }
        }

        public override void Disconnected(bool isConnected)
        {
            QuikIntegration.dde.QuikUtil.StartDDE();            
            Namespace.Clear();
        }
    }
}
